package com.xs.store.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

@Component
public class LoginFilter extends ZuulFilter {


    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
     * 过滤器顺序，越小越先执行
     * @return
     */
    @Override
    public int filterOrder() {
        return 4;
    }

    /**
     * 过滤器是否生效
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest httpRequest= requestContext.getRequest();
        //httpRequest.getRequestURI();//请求的路径除了域名之外的
       // httpRequest.getRequestURL();//整个地址

        if("/user/list".equalsIgnoreCase(httpRequest.getRequestURI())){
            return true;
        }
        return false;
    }

    /**
     * 过滤的业务逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("拦截了这个请求哟!");
        //通过Token去校验
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest request= requestContext.getRequest();
        //拿到请求中的token对象
        String token=request.getHeader("token");

        if(StringUtils.isBlank(token)){
            token=request.getParameter("token");
        }

        //登录校验逻辑 根据公司的情况自定义 JWT  可以直接搜索springboot JWT
        if(StringUtils.isBlank(token)){
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }
        return null;
    }
}
